extern crate reqwest ;//https 客户端访问

use std::io::Read;
use std::fs::File;
use std::error::Error;
use std::io::prelude::*;
use std::{thread, time};
use std::path::Path;
//命令行解析
use structopt::StructOpt;


use reqwest::header::HeaderMap;

//ex:  cargo run -- -u 911751 -p g:/download3
//命令行解析
#[derive(StructOpt)]
struct Opt {
    /// The pattern to look for
    /// 页面路径
    #[structopt(short ="u", long ="person")]
    person: String,
    /// The path to the file to read
    /// 保存目录 通过 from_os_str 转出 std::path::PathBuf类型
    #[structopt(parse(from_os_str),short ="p", long ="path")]
    path: std::path::PathBuf,
}

fn main() {
     //命令行解析
    let opt = Opt::from_args();
    //命令行解析
    println!("person={},path={}", opt.person,opt.path.to_str().unwrap());

    let url =format!("http://front-gateway.mtime.com/library/person/imageAll.api?personId={}",&opt.person);

    let response = reqwest::Client::builder()
    .danger_accept_invalid_certs(true)
    .build()
    .expect("客户端创建失败")
    .get(&*url)
    .send();

    let path =opt.path.to_str().unwrap();
    let mut  responseStr =String::from("");
    match response {
        Ok(mut r) => {

            responseStr =String::from( r.text().unwrap() )
        
        }
        Err(e) => {
           println!("{:?}",e);
        }
    }

    //println!("{}",&responseStr);

    let v: serde_json::Value = serde_json::from_str(&responseStr).unwrap();

    let data  =v.get("data").unwrap();

    let images =data.get("images").unwrap().as_array().unwrap();

    for img in images {
        let largeimgurl = img.get("imageOrigin").unwrap().as_str().unwrap();
        println!("dowdload:{}",&largeimgurl);
        //下载大图
        downloadfile(&String::from(largeimgurl),&path);

    }

    





    
}
//下载文件
fn downloadfile(url: &String ,path :&str) {
    let mut response =  reqwest::Client::builder()
    .danger_accept_invalid_certs(true)
    .build()
    .expect("客户端创建失败")
    .get(&*url)
    .send();

    match response {
        Ok(mut r) => {

            let filename =std::path::Path::new(&url).file_name().unwrap().to_str().unwrap();

            let mut file = std::fs::File::create(format!("{}/{}",path.to_owned(),filename.to_owned())).unwrap();
            r.copy_to(&mut file).unwrap();
        
            let sleep_time = time::Duration::from_millis(1000*1);
            thread::sleep(sleep_time);
        }

        Err(e) => {
           println!("{:?}",e);
        }
    }
    


}